package com.mrper.ui.main;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.RotateAnimation;

import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentBrandCategoryBinding;
import com.miguo.ui.databinding.GriditemChooseMenuBinding;
import com.mrper.ext.adapter.fragment.SwitchFragmentStateAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.dialog.ChooseMenuPopupWindow;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.model.entry.brand.BrandTypeInfoEntry;
import com.mrper.util.ViewUtil;
import com.mrper.util.http.HttpCommonUtil;
import com.mrper.util.http.listener.OnPublishBrandTypeListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by admin on 2016/3/10.
 * 品牌分类页面
 */
@ContentView(R.layout.fragment_brand_category)
public class FragmentBrandCategory extends BasicFragment<FragmentBrandCategoryBinding> implements ViewPager.OnPageChangeListener {

    public static final String TAG = FragmentBrandCategory.class.getSimpleName();

    private static final List<BrandTypeInfoEntry> brandTypes = new ArrayList<>();//品牌类型
    final List<FragmentBrandCategoryListContent> fragments = new ArrayList<>();//页面fragment
    private ChooseMenuPopupWindow<BrandTypeInfoEntry> chooseMenuPopupWindow;//类型菜单窗口

    @Override
    protected void initViews() {
        super.initViews();
        dataBinder.setOnClickEvent(this);
        HttpCommonUtil.getBrandTypes(new OnPublishBrandTypeListener() {
            @Override
            public void onPublish(List<BrandTypeInfoEntry> types) {
                initTabLayout(types); //初始化TabLayout布局
                brandTypes.addAll(types);//记录分类
                initChooseMenuWindow(types);//初始化用户选择类型菜单
            }
        });
    }

    /**
     * 初始化TabLayout控件
     **/
    @SuppressWarnings({"unchecked","deprecation"})
    private void initTabLayout(List<BrandTypeInfoEntry> categories) {
        int dataSize = categories.size();
        String[] titles = new String[dataSize];
        for (int index = 0; index < dataSize; index++) {
            String item = categories.get(index).name;
            titles[index] = item;
            dataBinder.tabCategory.addTab(dataBinder.tabCategory.newTab().setText(item), index == 0);
        }
        if (fragments.size() == 0) {
            for (int index = 0; index < dataSize; index++) {
                Bundle argument = new Bundle();
                argument.putInt("category_id", categories.get(index).id);
                FragmentBrandCategoryListContent fragment = ViewUtil.getFragmentInstance(FragmentBrandCategoryListContent.class, argument);
                fragments.add(fragment);
                if (index == 0) //初始化调用
                    fragments.get(index).initDataLoad();
            }
        }
        if (Build.VERSION.SDK_INT >= 23) dataBinder.flContainer.addOnPageChangeListener(this);
        else dataBinder.flContainer.setOnPageChangeListener(this);
        dataBinder.flContainer.setAdapter(new SwitchFragmentStateAdapter(getChildFragmentManager(), fragments, titles));
        dataBinder.tabCategory.setupWithViewPager(dataBinder.flContainer);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        fragments.get(position).initDataLoad();
        setCurrentSelectedIndex(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgArrowDown:
                showChooseMenuWindow();
                break;
            default:
                break;
        }
    }

    /** 初始化用户选择类型菜单  **/
    private void initChooseMenuWindow(List<BrandTypeInfoEntry> types) {
        if (chooseMenuPopupWindow == null) {
            chooseMenuPopupWindow = new ChooseMenuPopupWindow<>(context, types, new ChooseMenuPopupWindow.OnInitItemListener<BrandTypeInfoEntry>() {
                @Override
                public void onInitItem(GriditemChooseMenuBinding binder, BrandTypeInfoEntry item, int position, int selectedIndex) {
                    binder.setIsSelected(position == selectedIndex);
                    binder.setName(item.name);
                }
            }, new ChooseMenuPopupWindow.OnSelectedIndexChangedListener() {
                @Override
                public void onSelectedIndexChanged(int position) {
                    dataBinder.flContainer.setCurrentItem(position, true);
                }
            });
            chooseMenuPopupWindow.setOnVisibilityChangedListener(new ChooseMenuPopupWindow.OnVisibilityChangedListener() {
                @Override
                public void onVisibilityChanged(boolean isShow) {
                    RotateAnimation rotateAnimation = getRotateAnimation(isShow);
                    dataBinder.imgArrowDown.startAnimation(rotateAnimation);
                }

                @NonNull
                private RotateAnimation getRotateAnimation(boolean isShow) {
                    RotateAnimation rotateAnimation = new RotateAnimation(isShow ? 0 : 180, isShow ? 180 : 0,
                            RotateAnimation.RELATIVE_TO_SELF, 0.5F, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
                    rotateAnimation.setDuration(150);
                    rotateAnimation.setInterpolator(new AccelerateInterpolator());
                    rotateAnimation.setFillAfter(true);
                    return rotateAnimation;
                }
            });
        }else{
            onResume();
        }
    }

    /** 设置当前的索引项  **/
    private void setCurrentSelectedIndex(int index){
        if(chooseMenuPopupWindow!=null)
            chooseMenuPopupWindow.setSelectedIndex(index);
    }

    /** 显示用户类型化菜单  **/
    private void showChooseMenuWindow(){
        if(chooseMenuPopupWindow != null){
            int[] locations = new int[2];
            dataBinder.tabContainer.getLocationInWindow(locations);
            chooseMenuPopupWindow.setMenuGridLocation(0, locations[1] + dataBinder.tabContainer.getHeight()
                    + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? - statusBarHeight : 0));
            chooseMenuPopupWindow.showAtLocation(dataBinder.tabContainer, Gravity.TOP, 0, 0);
        }
    }

}
